package org.jeecg.modules.music.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.vo.category.CategoryVo;
import org.jeecg.modules.music.entity.MusCategory;
import org.jeecg.modules.music.mapper.MusCategoryMapper;
import org.jeecg.modules.music.model.CategoryIdModel;
import org.jeecg.modules.music.model.MusCategoryTreeModel;
import org.jeecg.modules.music.service.IMusCategoryService;
import org.jeecg.modules.music.util.FindsCategoriesChildrenUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service("musCategoryServiceImpl")
public class MusCategoryServiceImpl extends ServiceImpl<MusCategoryMapper, MusCategory> implements IMusCategoryService {

    @Transactional
    @Override
    public void saveCategoryData(MusCategory category, String username) {
        if (category != null && username != null) {
            if (category.getParentId() == null) {
                category.setParentId("");
            }

            String s = UUID.randomUUID().toString().replace("-", "");
            category.setId(s);
            // 先判断该对象有无父级ID,有则意味着不是最高级,否则意味着是最高级
            // 获取父级ID
            String parentId = category.getParentId();
            //update-begin--Author:baihailong  Date:20191209 for：部门编码规则生成器做成公用配置
            JSONObject formData = new JSONObject();
            formData.put("parentId",parentId);
            String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.MUS_CODE,formData);
            //update-end--Author:baihailong  Date:20191209 for：部门编码规则生成器做成公用配置
            category.setMusCode(codeArray[0]);
            String orgType = codeArray[1];
            category.setMusType(String.valueOf(orgType));
            category.setCreateTime(new Date());
            category.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
            this.save(category);
        }
    }

    @Override
    public List<MusCategoryTreeModel> queryTreeList(String ids) {
        List<MusCategoryTreeModel> listResult=new ArrayList<>();
        LambdaQueryWrapper<MusCategory> query = new LambdaQueryWrapper<MusCategory>();
        query.eq(MusCategory::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        if(oConvertUtils.isNotEmpty(ids)){
            query.in(true,MusCategory::getId,ids.split(","));
        }
        query.orderByAsc(MusCategory::getCategoryOrder);
        List<MusCategory> list= this.list(query);
        for (MusCategory category : list) {
            listResult.add(new MusCategoryTreeModel(category));
        }
        return  listResult;
    }

    @Override
    public List<MusCategoryTreeModel> queryTreeList() {
        LambdaQueryWrapper<MusCategory> query = new LambdaQueryWrapper<MusCategory>();
        query.eq(MusCategory::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        query.orderByAsc(MusCategory::getCategoryOrder);
        List<MusCategory> list = this.list(query);
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<MusCategoryTreeModel> listResult = FindsCategoriesChildrenUtil.wrapTreeDataToTreeList(list);
        return listResult;
    }

    @Override
    public List<CategoryIdModel> queryCategoryIdTreeList() {
        LambdaQueryWrapper<MusCategory> query = new LambdaQueryWrapper<MusCategory>();
        query.eq(MusCategory::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        query.orderByAsc(MusCategory::getCategoryOrder);
        List<MusCategory> list = this.list(query);
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<CategoryIdModel> listResult = FindsCategoriesChildrenUtil.wrapTreeDataToDepartIdTreeList(list);
        return listResult;
    }

    @Override
    public boolean updateCategoryDataById(MusCategory musCategory, String username) {
        if (musCategory != null && username != null) {
            musCategory.setUpdateTime(new Date());
            musCategory.setUpdateBy(username);
            this.updateById(musCategory);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<MusCategoryTreeModel> searchByKeyWord(String keyWord) {
        LambdaQueryWrapper<MusCategory> query = new LambdaQueryWrapper<MusCategory>();
        List<MusCategoryTreeModel> newList = new ArrayList<>();

        query.like(MusCategory::getCategoryName, keyWord);
        MusCategoryTreeModel model = new MusCategoryTreeModel();
        List<MusCategory> departList = this.list(query);
        if(departList.size() > 0) {
            for(MusCategory depart : departList) {
                model = new MusCategoryTreeModel(depart);
                model.setChildren(null);
                newList.add(model);
            }
            return newList;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatchWithChildren(List<String> ids) {
        List<String> idList = new ArrayList<String>();
        for(String id: ids) {
            idList.add(id);
            this.checkChildrenExists(id, idList);
        }
        this.removeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String id) {
        List<String> idList = new ArrayList<>();
        idList.add(id);
        this.checkChildrenExists(id, idList);
        //清空部门树内存
        //FindsDepartsChildrenUtil.clearDepartIdModel();
        boolean ok = this.removeByIds(idList);
        return ok;
    }

    @Override
    public List<CategoryVo> queryPlaylistCatList() {
        return baseMapper.queryPlaylistCatList();
    }

    /**
     * delete 方法调用
     * @param id
     * @param idList
     */
    private void checkChildrenExists(String id, List<String> idList) {
        LambdaQueryWrapper<MusCategory> query = new LambdaQueryWrapper<MusCategory>();
        query.eq(MusCategory::getParentId,id);
        List<MusCategory> departList = this.list(query);
        if(departList != null && departList.size() > 0) {
            for(MusCategory depart : departList) {
                idList.add(depart.getId());
                this.checkChildrenExists(depart.getId(), idList);
            }
        }
    }
}
